package org.example.model;

import org.dom4j.DocumentException;
import org.example.entity.Movie;
import org.example.service.CinemaService;
import org.example.service.ICinemaService;

import javax.swing.table.AbstractTableModel;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author TonySong
 * @date 2025/8/6 0006
 * @time 10:18
 */
public class CinemaTableModel extends AbstractTableModel {
    List<Movie> list;
    String[] columns;
    {
        Class<Movie> movieClass = Movie.class;
        //通过反射获取Movie类的所有属性
        Field[] fields =movieClass.getDeclaredFields();
        //创建大小为属性个数的String数组
        columns =new String[fields.length];
        try {

            for(int i=0;i<columns.length;i++){
                //打开字段（私有属性）访问
                fields[i].setAccessible(true);
                //获取各个字段名称并赋值给数组（用于显示表格的列标题）
                columns[i] = fields[i].getName();
            }
            ICinemaService cinemaService=new CinemaService();
            Map<String,Movie> data=cinemaService.readXmlToMap();
            if(data!=null && data.size()>0){
                System.out.println("获取数据成功！");
            }
            //利用Stram流将Map转换为list
            list= data.values().stream().collect(Collectors.toList());
            System.out.println(list);
        } catch (ParseException | IOException | DocumentException e) {
            throw new RuntimeException(e);
        }


    }
    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public int getColumnCount() {
        return columns.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        SimpleDateFormat sdf =new SimpleDateFormat("dd:mm");
         Movie movie = list.get(rowIndex);
         switch (columnIndex){
             case 0: return movie.getName();
             case 1: return movie.getDirection();
             case 2: return movie.getActor();
             case 3: return movie.getType();
             case 4: return movie.getPrice();
             case 5: return  sdf.format(movie.getPlayTime());
             default: return null;
         }

    }

    @Override
    public String getColumnName(int column) {
        return columns[column];
    }

    public List<Movie> getList() {
        return list;
    }

    public void setList(List<Movie> list) {
        this.list = list;
    }

    public String[] getColumns() {
        return columns;
    }

    public void setColumns(String[] columns) {
        this.columns = columns;
    }
}
